package com.example.demo001.handler;


import com.example.demo001.common.result.Result;
import com.example.demo001.constant.MessageConstant;
import com.example.demo001.constant.StatusCode;
import com.example.demo001.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.stream.Collectors;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler
    public Result<Object> exceptionHandler(BaseException ex){
        return Result.error(ex.getCode(), ex.getMsg() ,ex.getData());
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining(", "));
        return Result.error(StatusCode.PARAM_ERROR, errorMessage);
    }
    // 处理路径参数异常
    @ExceptionHandler(MissingPathVariableException.class)
    public Result<Object> handleMissingPathVariable(MissingPathVariableException ex) {
        return Result.error(StatusCode.PARAM_ERROR, "缺少路径参数：" + ex.getVariableName());
    }
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<Object> handleNoHandlerFound(NoHandlerFoundException ex) {
        return Result.error("请求路径不存在：" + ex.getRequestURL());
    }
    @ExceptionHandler
    public Result<Object> exceptionHandler(HttpMessageNotReadableException ex){

        return Result.error(StatusCode.PARAM_ERROR, MessageConstant.REQUEST_BODY_MISSING);
    }

    @ExceptionHandler
    public Result<Object> exceptionHandler(Exception ex){

        return Result.error(ex.getMessage());
    }


}
